"use client";

import { useCreateWorkspace, useTaskRun } from "@/service/align";
import { useInputLoadStore } from "@/store/input";
import { useCountStore } from "@/store/task";
import { AccountCircle } from "@mui/icons-material";
import NavigationIcon from "@mui/icons-material/Navigation";
import LoadingButton from "@mui/lab/LoadingButton";
import { Box, Button, TextField, Typography } from "@mui/material";
import Paper from "@mui/material/Paper";
import { styled } from "@mui/material/styles";
import { message } from "antd";
import { useRouter } from "next/navigation";
import { v4 as uuidv4 } from "uuid";

const Item = styled(Paper)(({ theme }) => ({
  backgroundColor: theme.palette.mode === "dark" ? "#1A2027" : "#fff",
  ...theme.typography.body2,
  padding: theme.spacing(1),
  textAlign: "center",
  color: theme.palette.text.secondary,
  flexGrow: 1,
  transition: theme.transitions.create(["height"], {
    duration: 1000,
  }),
}));

export default function StepThree(props: any) {
  const { email, setEmail, file_ids, pdb_ids, filter_options, clean } =
    useCountStore();
  const router = useRouter();
  const { clean: cleanInputStore } = useInputLoadStore();

  const { mutateAsync: createWorkspace, isPending: createWorkspaceLoading } =
    useCreateWorkspace();

  const { mutateAsync: taskRun, isPending: taskRunLoading } = useTaskRun();

  const handleRun = async () => {
    let workDir = "";
    let taskUUid = "";

    // if (!email) {
    //   message.warning("Please enter your email address");
    //   return;
    // }

    if (
      filter_options.is_filter &&
      !filter_options.bacterial_filter.length &&
      !filter_options.phage_filter.length &&
      !filter_options.prophage_filter.length
    ) {
      message.warning("Please select a filter");
      return;
    }

    if (!filter_options.is_filter && !filter_options.options.length) {
      message.warning("Please select a filter");
      return;
    }

    let user_id = localStorage.getItem("user_id");
    if (!user_id) {
      user_id = uuidv4();
      localStorage.setItem("user_id", user_id);
    }

    try {
      const createWorkspaceResponse: any = await createWorkspace({
        file_ids: [...file_ids],
        pdb_ids: [...pdb_ids],
        filter_options: {
          ...filter_options,
        },
        email: email,
        user_id: user_id,
      });
      workDir = createWorkspaceResponse.work_dir;
      taskUUid = createWorkspaceResponse.task_uuid;
      message.success("Workspace created successfully");
    } catch (error: any) {
      if (error?.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error("Failed to create workspace");
      }
    }

    if (!workDir) {
      message.info("Workspace not found");
    }

    try {
      const taskRunResp = await taskRun({
        workspace_dir: workDir,
        email: email,
        user_id: user_id,
        task_uuid: taskUUid,
      });
      props.setOpen(true);
      router.push(`/home/task/${taskRunResp.task_id}`);
    } catch (error: any) {
      if (error?.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error("Failed to create Run");
      }
    } finally {
      clean();
      cleanInputStore();
    }
  };

  return (
    <Item
      sx={{
        height: "520px",
        position: "relative",
      }}
    >
      <Typography
        sx={{ flex: "1 1 100%", marginTop: "1rem", marginBottom: "1rem" }}
        variant="h6"
        component="div"
      >
        Commence <Box component="span">Execution</Box>
      </Typography>

      <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          marginTop: "7rem",
        }}
      >
        <Box
          sx={{
            width: "400px",
          }}
        >
          <div>
            <Typography variant="body1">
              Start running the algorithm or reselect
            </Typography>
          </div>
          <div
            style={{
              display: "flex",
              marginTop: "1rem",
              alignItems: "flex-end",
              justifyContent: "center",
            }}
          >
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <span
                style={{
                  marginRight: "7px",
                  fontSize: "17px",
                }}
              >
                (optional)
              </span>
              <AccountCircle
                sx={{ color: "primary.main", fontSize: "32px", mr: 1, my: 0.5 }}
              />
            </div>
            <TextField
              id="input-with-sx"
              label="Email Address"
              variant="standard"
              size="medium"
              value={email}
              onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                setEmail(event.target.value.trim());
              }}
              fullWidth
            />
          </div>
        </Box>
      </Box>
      {/* <Box sx={{ mt: 2, fontSize: "0.8rem" }}>
        Public email address：
        <span style={{ color: "#1976d2", paddingRight: "4px" }}>
          usergmps@gmail.com
        </span>{" "}
        Password：
        <span style={{ color: "#1976d2" }}>GMPSGMPS</span>
      </Box> */}
      <Box
        sx={{
          marginTop: "3rem",
        }}
      >
        <Button
          variant="text"
          sx={{
            padding: "0.5rem 2rem",
            textTransform: "none",

            marginRight: "1rem",
          }}
          onClick={() => props.handleLastStep(2)}
        >
          Last Step
        </Button>
        <LoadingButton
          loading={createWorkspaceLoading || taskRunLoading}
          color="primary"
          variant="contained"
          onClick={() => handleRun()}
          sx={{ textTransform: "none" }}
        >
          <NavigationIcon sx={{ mr: 1 }} />
          Start Run
        </LoadingButton>
      </Box>
    </Item>
  );
}
